<!--
 * @description:添加津贴
 * @Author: Coder
 * @Date: 2019-12-11 11:13:10
 * @LastEditors: Coder
 -->
<template>
  <div>
    <a-drawer
      title="添加津贴方案"
      placement="right"
      :closable="false"
      destroyOnClose
      :visible="visible"
      :width="540"
      @close="visible = false"
    >
      <!-- 展示员工信息档案 -->
      <a-form>
        <a-form-item label="方案名称 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
          <a-input v-model="editorData.name" :maxLength="50" />
        </a-form-item>
        <a-form-item label="备注 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
          <a-input v-model="editorData.remark" />
        </a-form-item>
        <div class="form_item bg_gray mb20">
          员工薪资信息
          <a-checkbox class=" flr ">删除</a-checkbox>
        </div>
        <!-- 添加 -->
        <div v-for="(item, index) in editorData.subsidyInfoDOList" :key="index">
          <a-form-item label="津贴名称 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
            <a-input v-model="item.name" />
          </a-form-item>
          <a-form-item label="每月固定 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
            <a-select style="width: 100%" v-model="item.sendDate">
              <a-select-option v-for="d in day" :value="d.key" :key="d.key">
                {{ d.value }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="金额 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
            <a-input v-model="item.amount" />
          </a-form-item>
        </div>
        <!-- 方式 -->
        <a-form-item class="sub_tit" label="适用计税方式 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
          <a-radio-group :options="radioOptions" v-model="editorData.taxMethod" />
        </a-form-item>
        <!-- 范围 -->
        <a-form-item class="sub_tit" label="适用出勤范围 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
          <a-switch v-model="editorData.attendanceRange" />
        </a-form-item>
        <!-- 类型 -->
        <a-form-item class="sub_tit" label="适用聘用类型 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
          <a-checkbox-group v-model="editorData.applyToProgVO.employType">
            <a-row>
              <a-col style="margin-top: 10px" :span="8">
                <a-checkbox value="6">正式</a-checkbox>
              </a-col>
              <a-col style="margin-top: 10px" :span="8">
                <a-checkbox value="1">实习</a-checkbox>
              </a-col>
              <a-col style="margin-top: 10px" :span="8">
                <a-checkbox value="2">劳务</a-checkbox>
              </a-col>
              <a-col style="margin-top: 10px" :span="8">
                <a-checkbox value="3">顾问</a-checkbox>
              </a-col>
              <a-col style="margin-top: 10px" :span="8">
                <a-checkbox value="4">返聘</a-checkbox>
              </a-col>
              <a-col style="margin-top: 10px" :span="8">
                <a-checkbox value="5">外包</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>
        <!-- 范围 -->
        <a-form-item class="sub_tit" label="适用范围 :" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
          <a-checkbox-group v-model="editorData.applyToProgVO.employRange">
            <a-row type="flex">
              <a-col style="margin-top: 10px">
                <a-checkbox value="1">按部门</a-checkbox>
              </a-col>
              <a-col style="margin-top: 10px" v-if="false">
                <a-checkbox value="2">按职级</a-checkbox>
              </a-col>
              <a-col style="margin-top: 10px">
                <a-checkbox value="3">按岗位</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>
        <!-- 添加范围员工 -->
        <a-form-item
          v-if="editorData.applyToProgVO.employRange.includes('1')"
          class="sub_tit"
          label="适用范围 :"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
        >
          <a-popover title="添加部门或员工" placement="leftBottom" trigger="click" v-model="visible2">
            <template slot="content">
              <a-tree style="min-width: 400px" :treeData="treeData" @select="onSelect" :replaceFields="replaceFields" />
            </template>
            <a-button icon="plus-square" @click="showDepPeo"> 添加适用部门或员工</a-button>
          </a-popover>
          <a-row type="flex">
            <a-col class="mg_b6" v-for="(item, i) in editorData.applyToProgVO.applyToProgDepVOList" :key="i">
              <a-tag v-if="item.type == 1" color="#6A66F6">
                部门: {{ item.empName }}
                <a-icon type="close-circle" @click="delItem(item, editorData.applyToProgVO.applyToProgDepVOList)" />
              </a-tag>
              <a-tag v-if="item.type == 2" color="green">
                员工:{{ item.empName }}
                <a-icon type="close-circle" @click="delItem(item, editorData.applyToProgVO.applyToProgDepVOList)" />
              </a-tag>
            </a-col>
          </a-row>
        </a-form-item>
        <!-- 添加岗位 -->
        <a-form-item
          v-if="editorData.applyToProgVO.employRange.includes('3')"
          class="sub_tit"
          label="适用范围 :"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
        >
          <a-popover placement="leftBottom" title="添加岗位" trigger="click" v-model="visible3">
            <template slot="content">
              <a-tree style="min-width: 400px" :treeData="posList" @select="onSelectPos" :replaceFields="replaceFieldsPos" />
            </template>
            <a-button icon="plus-square" @click="showGangwei"> 添加适用岗位</a-button>
          </a-popover>
          <a-row type="flex">
            <a-col v-for="(item, i) in editorData.applyToProgVO.applyToProgPositionVOList" :key="i">
              <a-tag color="cyan">
                岗位: {{ item.positionName }}
                <a-icon type="close-circle" @click="delItemGw(item, editorData.applyToProgVO.applyToProgPositionVOList)" />
              </a-tag>
            </a-col>
          </a-row>
        </a-form-item>
      </a-form>

      <a-modal mask v-model="childrenDrawer" :width="800" class="m_h99" title="添加员工" @ok="handleOk" okText="确认" cancelText="取消">
        <a-checkbox-group :indeterminate="true" style="width:100%" @change="onChangeUser">
          <a-row>
            <a-checkbox
              class="user_item mg_r10 mg_b10 pd10"
              v-for="item in users"
              :key="item.id"
              :value="item.id"
              style="width: 30%;margin-left: 0px"
            >
              <a-row type="flex" align="middle">
                <a-col :span="8">
                  员工
                </a-col>
                <a-col :span="16">
                  <a-row>{{ item.name }}</a-row>
                  <a-row>{{ item.phone }}</a-row>
                </a-col>
              </a-row>
            </a-checkbox>
          </a-row>
        </a-checkbox-group>
      </a-modal>
      <footer class="footer">
        <a-button @click="editor" class="btn_bag">保存</a-button>
        <a-button @click="visible = false">取消</a-button>
      </footer>
    </a-drawer>
  </div>
</template>

<script>
import { Check, CheckWork } from "@/api/check";
import { Wages, WagesSet, Common } from "@/api/wages";
export default {
  props: {
    allOptions: {
      type: Object,
      default: () => ({
        show: true,
        obj: {}
      })
    }
  },
  data() {
    return {
      treeData: [],
      /* 岗位 */
      posList: [],
      /* 岗位树 */
      replaceFieldsPos: {
        children: "positionChildList",
        title: "name"
      },
      /* tree替换 */
      replaceFields: {
        children: "childList",
        title: "depName"
      },
      visible2: false,
      visible3: false,
      /* 选择部门表 */
      deps: [],
      /* 选择员工表 */
      users: [],
      depList: [], // 部门列表
      userList: [], // 员工列表
      radioOptions: [
        { label: "税前", value: 1 },
        { label: "税后", value: 2 }
      ],
      add: false,
      del: false,
      visible: false,
      childrenDrawer: false,

      /* 修改/新增 detail */
      editorData: {
        companyId: this.$store.state.hr.companyId,
        applyToProgVO: {
          companyId: this.$store.state.hr.companyId,
          applyToProgDepVOList: [], // 适用部门
          applyToProgLevelVOList: [], // 适用职级
          applyToProgPositionVOList: [], // 适用岗位
          busProgId: "", // 业务方案ID
          busProgType: "", // 业务方案类型
          employType: [],
          employRange: [], // 适用范围（1：按部门，2：按职级，3：按岗位）
          gmtCreate: "", // 创建日期
          gmtModified: "", // 修改日期
          id: "", // 主键ID
          mutex: false
        },
        attendanceRange: true, // 适用出勤范围 是true,否false
        attendanceRangeDays: 1, // 出勤范围天数
        gmtCreate: "", // 创建日期
        gmtModified: "", // 修改日期
        id: "", // 主键ID
        name: "", // 方案名称
        remark: "", // 备注
        subsidyInfoDOList: [
          {
            companyId: this.$store.state.hr.companyId,
            amount: "", // 津贴金额
            createUserId: "",
            gmtCreate: null, // 创建日期
            gmtModified: null, // 修改日期
            id: "", // 主键ID
            modifiedUserId: "",
            name: "", // 津贴名称
            progId: "", // 津贴方案id
            siteId: "",
            type: 1, // 津贴类型1 每日出勤2每计薪日3每月固定4(每月按出勤日)5(每月按计薪日)
            valid: true
          }
        ], // 员工津贴配置信息集合
        taxMethod: 1 // 适用计税方式（1：税前，2：税后）
      }
    };
  },

  watch: {
    allOptions: {
      handler(val) {
        this.visible = val.show;
        if (val.obj.editorId) {
          this.getDetail();
          this.showDepPeo();
        }
      }
    }
  },
  computed: {
    day() {
      const box = [];
      let i = 1;
      while (i < 32) {
        box.push({ key: i, value: `${i}日` });
        i++;
      }
      return box;
    }
  },
  methods: {
    /* 展示岗位 */
    showGangwei() {
      Check({
        url: Common.posList,
        params: { companyId: this.$store.state.hr.companyId }
      }).then(({ data }) => {
        this.posList = data;
      });
    },
    /* 选择岗位 */
    onSelectPos(selectedKeys, info) {
      const { id: positionId, name: positionName } = info.node.dataRef;
      const isNew = this.editorData.applyToProgVO.applyToProgPositionVOList.find(val => val.positionId === positionId);
      if (isNew) {
        return this.$message.error("岗位存在,不可重复!!!");
      } else {
        this.editorData.applyToProgVO.applyToProgPositionVOList.push({
          positionId,
          progId: "",
          companyId: this.$store.state.hr.companyId,
          positionName
        });
      }
    },
    /* 获取津贴详情 */
    getDetail() {
      Wages({ url: WagesSet.detailItem + this.allOptions.obj.editorId }).then(({ data }) => {
        data.applyToProgVO.employType = data.applyToProgVO.employType.split(",").filter(item => item.trim());
        data.applyToProgVO.employRange = data.applyToProgVO.employRange.split(",").filter(item => item.trim());
        this.editorData = data;
      });
    },

    /* 展示部门员工 */
    showDepPeo() {
      Check({
        url: Common.depTreeList,
        params: { companyId: this.$store.state.hr.companyId }
      }).then(({ data }) => {
        this.treeData = data;
      });
    },
    /* 展示岗位员工 */
    showDep() {},
    /* 选择部门员工 */
    onSelect(selectedKeys, info) {
      /* this.visible2 = false */
      const { depName: empName, depId } = info.node.dataRef;

      const isNew2 = this.editorData.applyToProgVO.applyToProgDepVOList.find(val => val.depId === depId);

      if (isNew2) {
        if (info.node.dataRef.empInfoDOList && info.node.dataRef.empInfoDOList.length) {
          this.users = info.node.dataRef.empInfoDOList;
          this.childrenDrawer = true;
          this.visible2 = false;
        } else {
          this.$notification["warning"]({
            message: "部门成员为空!",
            description: "该部门下还没有成员,请先添加部门成员!!!"
          });
          /*  return this.$message.error('部门或成员存在,不可重复!!!'); */
        }
      } else {
        this.editorData.applyToProgVO.applyToProgDepVOList.push({
          depId,
          empName,
          companyId: this.$store.state.hr.companyId,
          progId: "",
          type: 1
        });
      }
    },
    /* 选择岗位 */
    onSelectDep(selectedKeys, info) {},
    /* 选择部门员工 */
    choseDep(env, val) {
      this.childrenDrawer = true;
      const dep = {
        depId: env,
        progId: "",
        type: 2,
        name: val[0]
      };
      if (this.deps.find(item => item.depId === env)) {
        return;
      } else {
        this.deps.push(dep);
      }
      this.users = this.getDepUsers(this.depList, env);
    },
    /* 取消部门 */
    delDep(i) {
      this.deps.splice(i, 1);
    },
    /* 取消选择员工 */
    delUser(i) {
      this.userList.splice(i, 1);
    },
    /* 选择员工 */
    onChangeUser(checkedValue, value) {
      this.userList = checkedValue.map((item, i) => {
        const obj = {
          companyId: this.$store.state.hr.computed,
          empName: `员工${i + 1}`,
          depId: item,
          gmtCreate: "",
          id: "",
          progId: "",
          type: 2
        };
        return obj;
      });
    },

    /* 获取部门下的员工 */
    getDepUsers(data, depId) {
      if (data.length) {
        return data.find(item => {
          if (item.childList) {
            this.getDepUsers(item.childList);
          }
          return item.depId === depId;
        });
      }
    },
    popupScroll() {},

    /* 处理部门需要色数据 */
    deepLoop(data) {
      const needData = [...data];
      const d = [];
      needData.map(val => {
        const { depName: title, depId: key, depId: value, childList: children } = val;
        val.title = title;
        val.value = value;
        val.key = key;
        val.children = children;
        if (val.childList) {
          this.deepLoop(val.childList);
        }
        d.push(val);
      });
      return d;
    },
    /* 获取部们列表 */
    getDepList() {
      Wages({ url: Common.depTreeList }).then(({ data }) => {
        if (data) this.depList = this.deepLoop(data);
      });
    },

    // 选择 删除添加
    delItem(item, arrs) {
      arrs.find((value, i, arr) => {
        if (value.depId === item.depId) return arr.splice(i, 1);
      });
    },
    /* 删除岗位 */
    delItemGw(item, arrs) {
      arrs.find((value, i, arr) => {
        if (value.positionId === item.positionId) return arr.splice(i, 1);
      });
    },
    // 交税方式

    // 关闭添加员工
    handleOk(e) {
      const copy = JSON.parse(JSON.stringify(this.editorData.applyToProgVO.applyToProgDepVOList));
      let dep = [...copy, ...this.userList];
      const obj = {};
      dep = dep.reduce(function(item, next) {
        obj[next.depId] ? "" : (obj[next.depId] = true && item.push(next));
        return item;
      }, []);
      this.editorData.applyToProgVO.applyToProgDepVOList = dep;
      this.childrenDrawer = false;
      this.userList = [];
    },
    handleCancel() {},
    // 添加员工
    showChildrenDrawer() {
      this.childrenDrawer = true;
    },
    /* 保存津贴设置 */
    editor() {
      if (this.allOptions.obj.editorId) {
        // put
        const copyData = JSON.parse(JSON.stringify(this.editorData));
        copyData.applyToProgUpdateDTO = copyData.applyToProgVO;
        copyData.applyToProgUpdateDTO.applyToProgDepAddDTOList = copyData.applyToProgVO.applyToProgDepVOList;
        copyData.applyToProgUpdateDTO.applyToProgLevelAddDTOList = copyData.applyToProgVO.applyToProgLevelVOList;
        copyData.applyToProgUpdateDTO.applyToProgPositionAddDTOList = copyData.applyToProgVO.applyToProgPositionVOList;
        copyData.companyId = this.$store.state.hr.companyId;
        copyData.applyToProgUpdateDTO.companyId = this.$store.state.hr.companyId;
        copyData.subsidyInfoDOList.forEach(item => {
          item.companyId = this.$store.state.hr.companyId;
        });
        copyData.applyToProgUpdateDTO.applyToProgDepAddDTOList.forEach(item => {
          item.companyId = this.$store.state.hr.companyId;
        });
        copyData.applyToProgUpdateDTO.applyToProgLevelAddDTOList.forEach(item => {
          item.companyId = this.$store.state.hr.companyId;
        });
        copyData.applyToProgUpdateDTO.applyToProgPositionAddDTOList.forEach(item => {
          item.companyId = this.$store.state.hr.companyId;
        });
        copyData.applyToProgUpdateDTO.employType = String(copyData.applyToProgUpdateDTO.employType);
        copyData.applyToProgUpdateDTO.employRange = String(copyData.applyToProgUpdateDTO.employRange);
        delete copyData.applyToProgVO;
        delete copyData.applyToProgUpdateDTO.applyToProgDepVOList;
        delete copyData.applyToProgUpdateDTO.applyToProgLevelVOList;
        delete copyData.applyToProgUpdateDTO.applyToProgPositionVOList;
        Wages({
          url: WagesSet.putAllowance,
          method: "PUT",
          data: copyData
        }).then(data => {
          if (data.success) {
            this.$notification["success"]({
              message: "成功",
              description: "修改成功"
            });
            this.$emit("cbFun", true);
            this.visible = false;
          }
        });
      } else {
        // post
        const copyData = JSON.parse(JSON.stringify(this.editorData));
        copyData.applyToProgAddDTO = copyData.applyToProgVO;
        copyData.applyToProgAddDTO.applyToProgDepAddDTOList = copyData.applyToProgVO.applyToProgDepVOList;
        copyData.applyToProgAddDTO.applyToProgLevelAddDTOList = copyData.applyToProgVO.applyToProgLevelVOList;
        copyData.applyToProgAddDTO.applyToProgPositionAddDTOList = copyData.applyToProgVO.applyToProgPositionVOList;
        copyData.applyToProgAddDTO.employType = String(copyData.applyToProgAddDTO.employType);
        copyData.applyToProgAddDTO.employRange = String(copyData.applyToProgAddDTO.employRange);
        delete copyData.applyToProgVO;
        delete copyData.applyToProgAddDTO.applyToProgDepVOList;
        delete copyData.applyToProgAddDTO.applyToProgLevelVOList;
        delete copyData.applyToProgAddDTO.applyToProgPositionVOList;

        Wages({
          url: WagesSet.postAllowance,
          method: "POST",
          data: copyData
        }).then(data => {
          if (data.success) {
            this.$notification["success"]({
              message: "成功",
              description: "新增成功"
            });
            this.$emit("cbFun", true);
            this.visible = false;
          }
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/coder.scss";
.form_item {
  padding-left: 20px;
  height: 48px;
  line-height: 48px;
  .mg_t8 {
    margin-top: 8px;
  }
  .sbu_tit {
    color: #9c9c9c;
  }
  .check-group-col {
    margin-top: 10px;
  }
}
.footer {
  box-shadow: 0px -1px 0px 0px rgba(232, 232, 232, 1);
  height: 68px;
  line-height: 68px;
  text-align: center;
}
.user_item {
  border: 1px solid #ccc;
}
</style>
